package com.cloud.message;

import com.cloud.utils.JSONUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttMessage;

/**
 * 消息对象
 */
public class QTMessageBuilder {

    /**
     * 消息主题
     */
    private String topic;
    /**
     * 消息级别
     */
    private Integer qos;

    /**
     * 消息内容
     */
    private Object message;

    public static QTMessageBuilder message(String topic, Integer qos, Object message) {
        QTMessageBuilder builder = new QTMessageBuilder();
        builder.setTopic(topic);
        builder.setQos(qos);
        builder.setMessage(message);
        return builder;
    }

    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }

    public Integer getQos() {
        return qos;
    }

    public void setQos(Integer qos) {
        this.qos = qos;
    }

    public Object getMessage() {
        return message;
    }

    public void setMessage(Object message) {
        this.message = message;
    }

    public MqttMessage build() {
        if (StringUtils.isEmpty(this.topic)) {
            throw new RuntimeException("未定义发送此消息的主题");
        }
        if (ObjectUtils.isEmpty(this.qos)) {
            throw new RuntimeException("未定义用于发送此消息的级别");
        }
        if (ObjectUtils.isEmpty(this.message)) {
            throw new RuntimeException("消息正文不能为空");
        }
        String str = JSONUtils.toJson(this.message);
        MqttMessage message = new MqttMessage();
        // 消息等级
        message.setQos(this.qos);
        // 如果重复消费,则把值改为true,然后发送一条空的消息,之前的消息就会覆盖,然后在改为false
        message.setRetained(false);
        message.setPayload(str.getBytes());
        return message;
    }

}
